<template>
  <div class="captchaWrap" v-show="showCaptcha">
      <div class="captcha_div" id="captcha_div" ref="captchaInner">
      </div>
  </div>
  
</template>

<script>
  import initNECaptcha from './captcha';
  export default {
    props: {
      mode: {
        type: String,
        default: 'popup' // "float"、"embed"、"popup"，即触发式、嵌入式、弹出式。
      },
      // 验证后的结果 成功或失败
      callback: {
        type: Function,
        default: null
      },
      // 是否显示验证
      showCaptcha: {
        type: Boolean,
        default: false
      },
      captchaClose: {
        type: Function,
        default: null
      }
    },
    data() {
      return {
        captchaIns: null
      }
    },
    methods: {
      show() {
        this.captchaIns.popUp();
        this.captchaIns.refresh();
      },
      hide() {
        this.captchaIns.close();
        // this.$emit('onClose', false)
      },
      // 让父组件自己验证
      verify(err, data) {
        this.callback && this.callback(err, data);
      },
      //让父组件自己关闭
      selfClose() {
        this.captchaClose && this.captchaClose();
      }

    },
    mounted() {
      const self = this;
      initNECaptcha({
          element: '#captcha_div',
          captchaId: 'deca75ae543c43bdb495e9a551829591',
          appendTo : this.$refs.captchaInner,
          mode: this.mode,
          width: '320px',
          onClose: this.selfClose,
          onVerify: this.verify,
          // enableClose : true
        },

        (instance) => {
          // 初始化成功后得到验证实例instance，可以调用实例的方法
          self.captchaIns = instance;
        }, (err) => {
          console.log(err);
          // 初始化失败后触发该函数，err对象描述当前错误信息
        })
    },
    watch: {
      showCaptcha: {
        handler: function (newVal) {
          // newVal ? this.show() : this.hide();
          if(newVal){
            this.show();
          }
        },
      }

    }
  };

</script>
<style scoped lang="scss">
  @include b(captchaWrap){
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
    z-index: 99999;
  }
  @include b(captcha_div){
    margin-top: 20%;
  }

</style>
